// utils/useCountdown.ts
import { ref, computed } from 'vue'

export function useCountdown(duration = 60) {
  const countdown = ref(0)
  let timer: ReturnType<typeof setInterval> | null = null

  const isCounting = computed(() => countdown.value > 0)

  const startCountdown = () => {
    // 如果倒计时已经开始，直接返回，防止重复启动
    if (isCounting.value) return

    countdown.value = duration
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer!)
        timer = null
      }
    }, 1000)
  }

  const resetCountdown = () => {
    clearInterval(timer!)
    timer = null
    countdown.value = 0
  }

  return {
    countdown,
    isCounting,
    startCountdown,
    resetCountdown,
  }
}
